// https://www.lintcode.com/problem/binary-tree-longest-consecutive-sequence/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root of binary tree
     * @return: the length of the longest consecutive sequence path
     */
    public int longestConsecutive(TreeNode root) {
        // write your code here
        return longestConsecutive(root, null, 0);
    }
    
    protected int longestConsecutive(TreeNode node, TreeNode parent, int curr) {
        if (node == null) {
            return 0;
        }
        if ((parent != null) && (node.val == (parent.val + 1))) {
            ++curr;
        } else {
            curr = 1;
        }
        int left_len = longestConsecutive(node.left, node, curr);
        int right_len = longestConsecutive(node.right, node, curr);
        return Math.max(curr, Math.max(left_len, right_len));
    }
}